package mao.thinkinjava.concurency.exchanger;

import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * @author Totoro
 * @date 2020/6/2
 * @explain:
 */
public class ExchangeProducer<T> implements Runnable {
    private Generator<T> generator;
    private Exchanger<List<T>> exchanger;
    private List<T> holder;
    private int maxSize;

    public ExchangeProducer(Generator<T> generator, Exchanger<List<T>> exchanger,List<T> holder,int size) {
        this.holder = holder;
        this.generator = generator;
        this.exchanger = exchanger;
        this.maxSize = size;
    }



    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            T next = generator.next();
            holder.add(next);
            System.out.println("produce "+ next);
            if (holder.size() == maxSize){
                try {
                    holder = exchanger.exchange(holder);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //恢复中断状态。
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
